#include <QCoreApplication>
#include <QFile>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    const char file[] = R"(F:\workspace\readEnglish\books\Jane-Eyre\1260\www.digilibraries.com@1260@1260-h@1260-h-5.htm)";
    QFile inFile(file);
    inFile.open(QFile::ReadOnly);
    QString s = inFile.readAll().simplified().replace("\"", "\\\"");
    // qDebug() << s;
    int pos = s.indexOf("CHAPTER XXXV");
    QStringList chapters {"XXXVI","XXXVII","CHAPTER XXXVIII—CONCLUSION"};
    QStringList contents;
    foreach(QString el, chapters) {
        int last = pos;
        pos = s.indexOf(QString("CHAPTER ").append(el));
        QString buf = s.mid(last, pos-last);
        int r = buf.lastIndexOf("<h2");
        buf = buf.left(r);
        contents << "<h2>" + buf;
    }
    pos = s.indexOf(QString("CHAPTER ").append(chapters.back()));
    contents << QString("<h2>") + s.mid(pos, s.indexOf("</body></html>")-pos);
    QFile outFile(R"(F:\workspace\readEnglish\books\Jane-Eyre\out.json)");
    outFile.open(QFile::WriteOnly);

    QStringList formatted;
    int count = 35;
    foreach(QString content, contents) {
        formatted << QString(R"({"_id":"%1","content":"%2","section":"%3"})").arg(QString::number(count), content, QString("Chapter ").append(QString::number(count)))
                     .simplified().append('\n');
        count++;
    }

    foreach(QString el, formatted) {
        outFile.write(el.toStdString().c_str());
    }


    return a.exec();
}
